import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; //第三方包：UI尺寸适配，设置响应式宽高
import 'package:video_player/video_player.dart'; //第三方包：视频播放
import 'package:orientation/orientation.dart';
import 'package:flutter_demo/util/net_utils.dart';
import 'package:flutter_demo/component/text_button.dart';

class DetailPage extends StatefulWidget {
  DetailPage({this.arguments});
  //定义一个arguments变量，接收路由参数
  final Map arguments;

  @override
  createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  var list = [];
  DeviceOrientation deviceOrientation;
  VideoPlayerController controller;
  bool fullScreen = false;
  bool noVideo = false;
  final TextEditingController textEditingController = new TextEditingController();

  //调用YY的直播视频源地址获取接口
  void _getVideoSrc(roomId) {
    print('@roomId');
    print(roomId);

    NetUtils.get('https://interface.yy.com/hls/new/get/' + roomId + '/' + roomId + '/1200', {
      "source": "wapyy",
      "callback": "jsonp2",
      "roomId": roomId,
    }).then((res) => _initVideoController(res));
  }

  //处理YY接口返回的JSONP数据，获得视频源地址
  void _initVideoController(res) {
    print('接口返回...');
    print(res);
    int numA = res.indexOf("\"hls\":\"");
    int numB = res.indexOf("\",\"");
    int numC = res.indexOf("\"\}");
    
    if (numA != -1) {
      String src = res.substring(numA + 7, numB > -1 ? numB : (numC > -1 ? numC : res.length - 3));

      print('视频源地址解析结果...');
      print(src);

      controller = VideoPlayerController.network(src);

      controller.initialize().then((value) {
        print('开始播放视频：' + src);
        controller.play();
        setState(() {});
      });
    } else {
      setState(() {
        noVideo = true;
      });
    }
  }

  void _toggleScreenMode () {
    if (deviceOrientation == DeviceOrientation.landscapeRight || deviceOrientation == DeviceOrientation.landscapeLeft) {
      setState(() {
        deviceOrientation = DeviceOrientation.portraitUp;
        fullScreen = false;
      });
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    } else {
      setState(() {
        deviceOrientation = DeviceOrientation.landscapeRight;
        fullScreen = true;
      });
      OrientationPlugin.forceOrientation(DeviceOrientation.landscapeRight);
    }
  }

  void _sendMsg(text) {
    if (text != '') {
      setState(() {
        list.insert(list.length, text);
      });
      textEditingController.clear();
    } else {
      print('没有输入任何内容');
    }
  }

  void _goBack() {
    Navigator.of(context).pop();
  }

  @override
  void initState() {
    super.initState();
    this._getVideoSrc(widget.arguments['roomId']);

    //监听陀螺仪，设置横屏竖屏
    OrientationPlugin.onOrientationChange.listen((value) {
      if (!mounted) return;

      setState(() {
        deviceOrientation = value;
        fullScreen = value == DeviceOrientation.landscapeRight || value == DeviceOrientation.landscapeLeft;
      });

      OrientationPlugin.forceOrientation(value);
    });
  }

  @override
  void dispose() {
   super.dispose();
   controller.pause();
   controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Scaffold(
      body: new Stack(
        children: [
          new Column(
            children: [
              new Stack(
                children: [
                  new Container(
                    height: fullScreen ? ScreenUtil.getInstance().setHeight(1334) : ScreenUtil.getInstance().setHeight(480),
                    color: Colors.white,
                    child: (controller != null && controller.value.initialized) ? new VideoPlayer(controller) : new Container(
                      alignment: Alignment.center,
                      color: Colors.black,
                      child: new Text(
                        noVideo ? '主播不在家...' : '加载中...',
                        style: new TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  new Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: new Container(
                      color: Color(0x40000000),
                      height: ScreenUtil.getInstance().setHeight(80),
                      alignment: Alignment.centerRight,
                      child: new Row(
                        children: [
                          new Expanded(
                            flex: 1, 
                            child: new Container(),
                          ),
                          new TextButton(
                            child: new Icon(
                              fullScreen ? Icons.fullscreen_exit : Icons.fullscreen,
                              color: Colors.white,
                              size: 28,
                            ),
                            padding: EdgeInsets.all(0),
                            onPressed: _toggleScreenMode,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              new Container(
                decoration: new BoxDecoration(
                  color: Color(0xfff3f3f3),
                  border: new Border(
                    top: new BorderSide(
                      color: Color(0xffe2e2e2), 
                      width: 1,
                    ),
                    bottom: new BorderSide(
                      color: Color(0xffe2e2e2), 
                      width: 1,
                    ),
                  ),
                ),
                padding: const EdgeInsets.only(left: 10, right: 10),
                height: fullScreen ? ScreenUtil.getInstance().setHeight(0) : ScreenUtil.getInstance().setHeight(80),
                child: new Row(
                  children: [
                    new Icon(
                      Icons.warning,
                      color: new Color(0xfff55d23),
                      size: 16,
                    ),
                    new Text(
                      '如果直播出现卡停，退出重进直播间即可', 
                      style: new TextStyle(
                        color: new Color(0xfff55d23),
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                height: fullScreen ? ScreenUtil.getInstance().setHeight(0) : ScreenUtil.getInstance().setHeight(774),
                color: Colors.white,
                padding: const EdgeInsets.all(10),
                child: new ListView(
                  padding: const EdgeInsets.all(0),
                  children: list.map((str) => 
                    new Container(
                      padding: const EdgeInsets.all(3),
                      child: new Text(str)
                    )
                  ).toList(),
                ),
              ),
            ],
          ),

          new Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: new Container(
              decoration: new BoxDecoration(
                color: Color(0xfff3f3f3),
                border: new Border(
                  top: new BorderSide(
                    color: Color(0xffe2e2e2), 
                    width: 1,
                  ),
                ),
              ),
              height: ScreenUtil.getInstance().setHeight(100),
              alignment: Alignment.centerRight,
              child: new Row(
                children: [
                  new Expanded(
                    flex: 1, 
                    child: new Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      child: new TextField(
                        controller: textEditingController,
                        decoration: new InputDecoration(
                          hintText: '请输入聊天内容',
                          fillColor: Colors.white,
                          filled: true,
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(left: 5, right: 5, top: 3, bottom: 4),
                        ),
                        onSubmitted: _sendMsg,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          new Positioned(
            top: 25,
            left: 5,
            child: new TextButton(
              child: new Icon(
                Icons.close,
                color: Colors.white,
                size: 28,
              ),
              padding: EdgeInsets.all(5),
              onPressed: _goBack,
            ),
          ),
        ],
      ),
    );
  }
}